<template>
    <div style="background-color: rgb(243, 243, 243);min-height:100vh;box-sizing: border-box;">
        <div style="height: 46px;"></div>
        <!-- 顶部导航栏 -->
        <div class="header">
            <van-nav-bar :title="status ? '注册' : '登录'" left-arrow @click-left="$router.replace('/home')" fixed>
                <template #right>
                    <van-icon name="ellipsis" size="18" />
                </template>
            </van-nav-bar>
        </div>

        <div class="main" style="display: flex;flex-direction: column;
        justify-content: center;align-items: center; margin-top: 30px; ">
            <img src="../../assets/logo.jpg" alt="" style="width: 115px;height: 115px;border-radius: 50%; " ref="img">

            <!-- 登录表单 -->

            <van-form @submit="onSubmit" style="margin-top: 15px;">
                <div style="background-color: #fff;border-radius: 10px;margin: 0 10px;" class="form">
                    <van-cell-group inset>
                        <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
                            :rules="[{ required: true, message: '请填写用户名' }]" />
                        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
                            :rules="[{ required: true, message: '请填写密码' }]" />

                        <van-field v-model="sign" name="签名" label="签名" placeholder="请输入个性签名"
                            :rules="[{ required: true, message: '请输入个性签名' }]" v-if="status" />

                        <van-field name="radio" label="性别" v-if="status">
                            <template #input>
                                <van-radio-group v-model="sex" direction="horizontal">
                                    <van-radio :name="1">男</van-radio>
                                    <van-radio :name="0">女</van-radio>
                                </van-radio-group>
                            </template>
                        </van-field>


                        <van-field v-model="secret_answer" name="密保" label="密保" placeholder="密保请输入密保"
                            :rules="[{ required: true, message: '请输入密保' }]" v-if="status" />

                    </van-cell-group>

                    <!-- 验证码 -->
                    <div style="padding: 0 15px 0 15px;" v-if="status">
                        <van-field center clearable label="验证码" placeholder="输入验证码" v-model="state.verify">
                            <template #button>
                                <Identify ref="verifyRef" />
                            </template>
                        </van-field>
                    </div>
                </div>
                <span style="display: inline-block; margin: 16px 0 0 25px;font-size: 12px; color: rgb(7, 124, 187);"
                    @click="changeStatus">
                    {{ status ? "已有账号，立即登录" : '立即注册' }}</span>
                <span
                    style="display: inline-block; margin: 16px 25px 0 0;font-size: 12px; color: rgb(7, 124, 187); float: right;"
                    @click="changePic">更换验证码</span>



                <!-- 登录按钮 -->
                <div style="margin: 20px;">
                    <van-button round block color="#1baeae" native-type="submit">
                        {{ status ? "注册" : '登录' }}
                    </van-button>

                </div>

            </van-form>
        </div>
    </div>
</template>

<script setup>
import { reactive, ref, toRefs, onMounted, watch } from "vue";
import Identify from "../../components/Identify.vue"; // 引入的验证码 
import { showSuccessToast, showFailToast, } from 'vant';
import { login, register } from '@/api/index.js'
import { useRouter } from "vue-router";
import getAvatar from '@/utils/avatar.js'
import { setToken } from '../../utils/token'
import useStore from '../../store/useStore'
import { setUserInfo, getUserInfo, resetLogin, lastLoginUser } from '../../utils/localStorage'

let store = useStore()
let router = useRouter()
let status = ref(false)
const username = ref('');
const password = ref('');
let avatar = ref(getAvatar())
let sign = ref('')
//console.log(avatar)

const sex = ref(1);
const secret_answer = ref();
//提交表单信息 发送请求
const onSubmit = () => {

    if (status.value) {
       
        if (verifyRef.value.imgCode === state.verify.toUpperCase()) {
            register({
                name: username.value, password: password.value, sign: sign.value,
                avatar: avatar.value, sex: sex.value, secret_answer: secret_answer.value
            }).then(res => {
                if (res.code == 1) {
                    showSuccessToast({
                        message: '注册成功',
                        duration: 500,
                    })
                    status.value = false
                    state.verify = ''
                    changePic()
                    password.value = ''
                }
            })
        } else {
            showFailToast({
                message: '验证码错误',
                duration: 500,
            })
        }
    } else {
        login({ name: username.value, password: password.value }).then(res => {
            if (res.code == 1) {
                showSuccessToast({
                    message: '登录成功',
                    duration: 300,
                })
                // console.log(res)
                //重置上次登陆
                if (lastLoginUser()) {
                    resetLogin()
                }
                //将token 和用户信息存入本地
                store.setInfo({ name: username.value, avatar: res.data.avatar, sex: res.data.sex, sign: res.data.sign })
                setUserInfo(username.value, { pwd: password.value, avatar: res.data.avatar, sex: res.data.sex, sign: res.data.sign, lastLogin: true })
                setToken(res.data.token, res.data.expire_in)
                router.replace('/home')
            }
        })
    }


};

const verifyRef = ref(null);

const state = reactive({
    verify: "",
});
//点击重绘
function changePic() {
    verifyRef.value.handleDraw()
}
//更换状态
function changeStatus() {
    status.value = !status.value
    state.verify = ''
}
//监听输入框用户名的变化 改变头像
let img = ref()
watch(username, (val) => {
    getUserInfo(val) ? img.value.src = getUserInfo(val).avatar : img.value.src = "http://tubie.gitee.io/maluyanxuan/img/mlogo.0fbc4c3c.png"

})



</script>

<style scoped >
:deep() .form .van-field__label {
    width: 70px;
}

:deep() .van-nav-bar .van-icon {
    color: #1BAEAE;
}
</style>